package main

import (
	"go-scripts/services"
	"go-scripts/models"
	"gopkg.in/mgo.v2"
	"go-scripts/common"
	"runtime"
	"gopkg.in/mgo.v2/bson"
)

var redisService = services.GetRedisService()
var model = models.GetModel()
var EffectTopic *mgo.Collection
var logger = common.GetLogger()
var TmpNews *mgo.Collection

func init()  {
	var err error
	EffectTopic, err = model.GetModelCollection("EffectTopic")
	checkErr(err)
	TmpNews, err = model.GetModelCollection("TmpNews")
	checkErr(err)
}
func main() {
	defer func() {
		if e := recover(); e!= nil {
			logger.Fatal(e)
		}
	}()
	runtime.GOMAXPROCS(runtime.NumCPU())
	rids, err := redisService.GetTopInfoRids()
	checkErr(err)
	for _, rid :=  range rids {
		logger.Info(rid)
		processOneRid(rid)
	}
	logger.Info("success")
}

func checkErr(err error)  {
	if err != nil {
		panic(err)
	}
}

func processOneRid(rid string)  {
	removeOneEffectTopic(rid)
	updateEffectTopic(rid)
	updateTmpNews(rid)
	redisService.RemoveOneTopInfoRid(rid)
}
//删除主题
func removeOneEffectTopic(rid string)  {
	//查询hylandaId
	effectTopic := new(models.EffectTopic)
	EffectTopic.Find(bson.M{
		"rid": rid,
	}).One(&effectTopic)
	if effectTopic.HylandaId == "" {
		logger.Error("hylandaId不存在")
		return
	}
	err := common.CloseOneTopic(effectTopic.HylandaId)
	if err != nil {
		logger.Error(err)
	}
	err = common.DeleteOneTopic(effectTopic.HylandaId, EffectTopic)
	if err != nil {
		logger.Error(err)
	}
}
//更新tmpnews,设置状态0
func updateTmpNews(rid string)  {
	TmpNews.Update(bson.M{
		"_id": bson.ObjectIdHex(rid),
	}, bson.M{
		"$set": bson.M{
			"status": -1,
		},
	})
}
//更新effectTopic,设置disabled true
func updateEffectTopic(rid string)  {
	EffectTopic.Update(bson.M{
		"rid": rid,
	}, bson.M{
		"$set": bson.M{
			"disabled": true,
		},
	})
}